<script setup>
import {onMounted, onUnmounted, reactive, ref} from 'vue';
import {Lock, Postcard, User} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";
import request from "@/utils/request.js";
import router from "@/router/index.js";
import {loginService} from "@/api/auth.js";

// 表单数据
const form = reactive({
  username: '',
  password: '',
  verifyCode: '',
  verifyCodeUuid: '',
});

const validateUsername = (rule, value, callback) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // 邮箱正则
  const phoneRegex = /^1[3-9]\d{9}$/;             // 手机号正则（中国大陆）

  if (!value.trim()) {
    callback(new Error('用户名 / 邮箱 / 手机号不能为空'));
  } else if (
      !(value.length >= 8 && value.length <= 16) &&
      !emailRegex.test(value) &&
      !phoneRegex.test(value)
  ) {
    callback(new Error('请输入合法的用户名、邮箱或手机号'));
  } else {
    callback();
  }
};

const rules = {
  username: [
    {required: true, validator: validateUsername, trigger: 'blur'}
  ],
  password: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
    {min: 8, max: 16, message: '密码长度应在 8 ~ 16 位之间', trigger: 'blur'}
  ],
  verifyCode: [
    {required: true, message: '验证码不能为空', trigger: 'blur'}
  ]
};

const formRef = ref();

// 验证码图片
const captchaUrl = ref('')

// 获取验证码
const getCaptcha = async () => {
  try {
    if (captchaUrl.value) {
      URL.revokeObjectURL(captchaUrl.value)
    }

    const res = await request.get('/auth/getCaptcha', {
      responseType: 'arraybuffer' // 👈 使用 arraybuffer 而不是 blob
    })

    form.verifyCodeUuid = res.headers['verifycodeuuid']

    const blob = new Blob([res.data], {type: 'image/png'})
    captchaUrl.value = URL.createObjectURL(blob)

  } catch (error) {
    ElMessage.error('获取验证码失败，请刷新重试')
  }
}


// 刷新验证码
const refreshCaptcha = () => {
  form.verifyCode = ''
  getCaptcha()
}

// 组件挂载时加载验证码
onMounted(() => {
  getCaptcha()
})

// 组件卸载时释放 URL 资源
onUnmounted(() => {
  if (captchaUrl.value) {
    URL.revokeObjectURL(captchaUrl.value)
  }
})

// 登录方法
const handleLogin = async () => {

  const valid = await formRef.value.validate().catch(() => false);
  if (valid) {
    const res = await loginService(form)

    if (res.data.code === '200') {
      localStorage.setItem('user', JSON.stringify(res.data.data))
      void router.push('/home')
      ElMessage.success('登录成功')
    } else {
      refreshCaptcha()
      ElMessage.error(res.data.message)
    }
  } else {
    ElMessage.error("请填写完整信息")
  }
}

const handleButton = () => {
  ElMessage.warning('功能正在开发')
}

</script>

<template>
  <div class="login-container">
    <div class="content">
      <div class="header">
        <div class="header-img">
          <img src="../assets/logo.jpg" style="width: 50px" alt="图像无法加载"/>
        </div>
        <h2 style="margin-top: 10px">NOVA ADMIN</h2>
      </div>
      <div class="main">
        <el-form :model="form" :rules="rules" ref="formRef" style="max-width: 600px">
          <el-form-item prop="username">
            <el-input v-model="form.username" placeholder="用户名 / 邮箱 / 手机号">
              <template #prefix>
                <el-icon size="18">
                  <User/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input show-password placeholder="请输入密码" type="password" style="margin-top: 10px"
                      v-model="form.password">
              <template #prefix>
                <el-icon size="18">
                  <Lock/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="verifyCode">
            <el-input v-model="form.verifyCode" placeholder="验证码" style="width: 220px; margin-top: 10px">
              <template #prefix>
                <el-icon size="18">
                  <Postcard/>
                </el-icon>
              </template>
            </el-input>
            <div style="width: 140px;margin-left: 18px ;height: 40px;margin-top: 10px">
              <img v-if="captchaUrl" :src="captchaUrl"
                   style="width: 140px; height: 40px;border: 2px solid #DCDFE6 ;cursor:pointer"
                   @click="refreshCaptcha"
                   alt="图像无法加载"/>
              <div style="width: 140px; height: 40px; border: 1px solid #DCDFE6" v-else></div>
            </div>
          </el-form-item>

          <el-form-item>
            <div style="width: 100%;display: flex; justify-content: space-between; align-items: center;">
              <div style="cursor: pointer; color: #409EFF;" @click="router.push('/register')">没有帐号？点此注册</div>
              <div style="cursor: pointer; color: #409EFF;" @click="router.push('/forget-password')">
                已有帐号，忘记密码？
              </div>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button style="width: 100% ;height: 40px; font-size: 18px" type="primary"
                       @click="handleLogin">登 录
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="footer">
        <div style="display: flex; justify-content: space-between; width: 100%;">
          <el-button @click="handleButton">QQ</el-button>
          <el-button @click="handleButton">微信</el-button>
          <el-button @click="handleButton">支付宝</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>

.login-container {
  height: 100vh;
  background-image: url('@/assets/login/background.png');
  background-size: cover;
  background-position: center;
  display: flex;
  justify-content: center;
  align-items: center;

  .content {
    width: 650px;
    height: 530px;
    border-radius: 12px;
    background-color: #FFF;

    .header {
      margin-top: 30px;

      .header-img {
        display: flex;
        justify-content: center;
      }

      h2 {
        text-align: center;
      }

    }

    .main {
      margin: 20px auto;
      width: 380px;
      height: 300px;
      display: flex;
    }

    .footer {
      margin: 20px auto;
      height: 50px;
      width: 380px;
      display: flex;
    }

  }
}

:deep() .el-input__wrapper {
  height: 40px;
}
</style>